package org.chen.wordwave.act.game;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.hjq.toast.Toaster;

import org.chen.wordwave.Api.ApiClient;
import org.chen.wordwave.Api.ApiService;
import org.chen.wordwave.R;
import org.chen.wordwave.bean.SignIn;
import org.chen.wordwave.bean.UserInfo;
import org.chen.wordwave.init.WordInit;
import org.chen.wordwave.tools.user.UserUtils;

import java.util.HashMap;
import java.util.Map;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class FootballWordGame extends AppCompatActivity {

    private TextView tvTitle, tvScore, tvHint,tv_game_instructions;
    private ImageView ivHintImage;
    private GridLayout glCrossword;
    private Button btnSubmit, btnReset;
    private int score = 0;
    private Map<String, String> crosswordMap; // 记录单词格的id和对应的正确字母
    private Map<String, Button> buttonMap; // 记录单词格的id和对应的Button
    private String[] words = {"GOAL", "BALL", "KICK", "TEAM", "PASS", "COACH", "SCORE", "MATCH", "FIELD", "FANS"};
    private int currentWordIndex = 0;
    private Map<String, Integer> wordImages;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.football_word_game_act);

        tvTitle = findViewById(R.id.tv_title);
        tvScore = findViewById(R.id.tv_score);
        tvHint = findViewById(R.id.tv_hint);
        ivHintImage = findViewById(R.id.iv_hint_image);
        glCrossword = findViewById(R.id.gl_crossword);
        btnSubmit = findViewById(R.id.btn_submit);
        btnReset = findViewById(R.id.btn_reset);
        tv_game_instructions = findViewById(R.id.tv_game_instructions);

        wordImages = new HashMap<>();
        wordImages.put("GOAL", R.drawable.goal_gif);
        wordImages.put("BALL", R.drawable.ball_gif);
        wordImages.put("KICK", R.drawable.kick_gif);
        wordImages.put("TEAM", R.drawable.team_gif);
        wordImages.put("PASS", R.drawable.pass_gif);
        wordImages.put("COACH", R.drawable.coach_gif);
        wordImages.put("SCORE", R.drawable.score_gif);
        wordImages.put("MATCH", R.drawable.match_gif);
        wordImages.put("FIELD", R.drawable.field_gif);
        wordImages.put("FANS", R.drawable.fans_gif);

        setupCrossword();

        btnSubmit.setOnClickListener(v -> submitCrossword());
        btnReset.setOnClickListener(v -> resetCrossword());

        // 初始化提示
        updateHint();

        tv_game_instructions.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showRulesDialog();
            }
        });

    }

    private void setupCrossword() {
        crosswordMap = new HashMap<>();
        buttonMap = new HashMap<>();

        // 添加单词格
        addWordButton("word1_letter1", words[currentWordIndex].charAt(0) + "");
        addWordButton("word1_letter2", words[currentWordIndex].charAt(1) + "");
        addWordButton("word1_letter3", words[currentWordIndex].charAt(2) + "");
        addWordButton("word1_letter4", words[currentWordIndex].charAt(3) + "");
    }

    private void addWordButton(String buttonId, String correctLetter) {
        int resID = getResources().getIdentifier(buttonId, "id", getPackageName());
        Button wordButton = findViewById(resID);
        crosswordMap.put(buttonId, correctLetter);
        buttonMap.put(buttonId, wordButton);

        wordButton.setOnClickListener(v -> showLetterSelectionDialog(buttonId, wordButton));
    }

    private void showLetterSelectionDialog(String buttonId, Button wordButton) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.select_word);

        // 示例：显示A-Z的字母选择
        String[] letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".split("");
        builder.setItems(letters, (dialog, which) -> {
            String selectedLetter = letters[which];
            wordButton.setText(selectedLetter);
        });

        AlertDialog dialog = builder.create();
        dialog.show();
    }

    @SuppressLint("SetTextI18n")
    private void submitCrossword() {
        boolean isCorrect = true;
        for (Map.Entry<String, String> entry : crosswordMap.entrySet()) {
            String buttonId = entry.getKey();
            String correctLetter = entry.getValue();
            Button wordButton = buttonMap.get(buttonId);
            assert wordButton != null;
            if (!correctLetter.equals(wordButton.getText().toString())) {
                isCorrect = false;
                break;
            }
        }

        if (isCorrect) {
            score += 10;
            tvScore.setText(getString(R.string.football_score) + score);
            Toaster.show(getString(R.string.congratulations_you_got_it_right));
            nextWord();
        } else {
            Toaster.show(getString(R.string.Unfortunately));
            gameOver();
        }
    }

    private void nextWord() {
        currentWordIndex++;
        if (currentWordIndex >= words.length) {
            Toaster.show(getString(R.string.congratulations_to_you));
            gameOver();
            return;
        }

        updateHint();
        resetCrossword();
    }

    @SuppressLint("SetTextI18n")
    private void updateHint() {
        String hint = words[currentWordIndex].charAt(0) + "____";
        tvHint.setText(getString(R.string.hint) + hint);
        ivHintImage.setImageResource(wordImages.get(words[currentWordIndex]));
    }

    private void resetCrossword() {
        for (Button wordButton : buttonMap.values()) {
            wordButton.setText("");
        }

        // 更新单词格
        crosswordMap.clear();
        buttonMap.clear();
        setupCrossword();
    }

    private void gameOver() {
        if (score >= 100){
            new Thread(() -> {
                UserInfo userInfo = UserUtils.getUserInfo(this);
                SignIn signIn = new SignIn();
                signIn.setMember(userInfo.isMember());
                signIn.setPoints(userInfo.getPoints() + 100);
                signIn.setEmail(WordInit.userInfo.getEmail());
                ApiService apiService = ApiClient.getClient(this).create(ApiService.class);
                apiService.gift(signIn).enqueue(new Callback<SignIn>() {
                    @Override
                    public void onResponse(Call<SignIn> call, Response<SignIn> response) {
                        Toaster.show(getString(R.string.prize_100,100));
                    }

                    @Override
                    public void onFailure(Call<SignIn> call, Throwable t) {
                        Toaster.show(getString(R.string.prize_100_error));
                    }
                });
            }).start();
        }
        Toaster.show(getString(R.string.game_over) + score);
        score = 0;
        tvScore.setText(R.string.score_0);
        currentWordIndex = 0;
        updateHint();
        resetCrossword();
    }

    private void showRulesDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.game_info_football);
        builder.setMessage(getString(R.string.game_info_football_content));
        builder.setPositiveButton(R.string.yes, (dialog, id) -> dialog.dismiss());
        AlertDialog dialog = builder.create();
        dialog.show();
    }
}
